package com.vvitt.kotlinhiltcarhome.repository

import androidx.paging.*
import com.vvitt.flowpractice.common.PAGING_INITIAL_PAGE_SIZE
import com.vvitt.flowpractice.common.PAGING_PAGE_SIZE
import com.vvitt.kotlinhiltcarhome.db.CarBrandDataBase
import com.vvitt.kotlinhiltcarhome.entity.CarBrandEntity
import com.vvitt.kotlinhiltcarhome.mapper.Mapper
import com.vvitt.kotlinhiltcarhome.model.CarBrandItemModel
import com.vvitt.kotlinhiltcarhome.net.CarBrandApi
import com.vvitt.kotlinhiltcarhome.net.RemoteCarBrandMediator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map

/**
 * @ClassName CarBrandRepositoryImpl
 * @author please call me police uncel
 * @since 2023/5/25.
 * @email 110
 * @Version: V1.0.0
 * @desciption 汽车品牌 Repository 实现类
 **/
class CarBrandRepositoryImpl(
    private val api : CarBrandApi,
    private val database : CarBrandDataBase,
    private val mapper2ItemModel : Mapper<CarBrandEntity, CarBrandItemModel>
    ) : BaseRepository {
    override fun fetchCarBrandList(): Flow<PagingData<CarBrandItemModel>> {
//        //TODO: 是否需要加这个注解==============================
//        @OptIn(ExperimentalPagingApi::class)
        return Pager(
            config = PagingConfig(
                pageSize = PAGING_PAGE_SIZE,
                prefetchDistance = 1,
                initialLoadSize = PAGING_INITIAL_PAGE_SIZE
            ),
            //请求网络数据，放入数据库
            remoteMediator = RemoteCarBrandMediator(api,database)
        ){
            //从数据库拿到数据
            database.carBrandDao().getCarBrandList()
        }.flow
            .flowOn(Dispatchers.IO)
            .map { pagingData ->
                //对数据进行转换，给到UI展示
                pagingData.map { mapper2ItemModel.map(it) }
            }
    }


}